import React from 'react';
import {Table, Card} from 'antd';
import PropTypes from 'prop-types';
import {conventEnumValueToString, formatAmount, formatDateTime, exportDownload} from '../utils';
import {transportType, paymentType, partOrderPriceTerms, partContractInvoiceStatus} from '../Enum';
import {PERMISSION} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {hasPermissions} from './utils';
import {getListExcelDesc, getInvoiceExcelDesc, getNoticeExcelDesc, getOrderExcelDesc, getPackingExcelDesc, getConfirmExcelDesc} from './api';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATE_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import DropdownMenu from 'Shared/components/DropdownMenu';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    listExcelConfirm = id => {
        this.setState({
            loading: true
        });
        getListExcelDesc(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    invoiceExcelConfirm = id => {
        this.setState({
            loading: true
        });
        getInvoiceExcelDesc(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    noticeExcelConfirm = id => {
        this.setState({
            loading: true
        });
        getNoticeExcelDesc(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    orderExcelConfirm = id => {
        this.setState({
            loading: true
        });
        getOrderExcelDesc(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    packingExcelConfirm = id => {
        this.setState({
            loading: true
        });
        getPackingExcelDesc(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    confirmExcelConfirm = id => {
        this.setState({
            loading: true
        });
        getConfirmExcelDesc(id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
        });
    };
    onPrintPdf = e => {
        e.stopPropagation();
        window.open(`/parts/print/reportpdf.html?id=${e.currentTarget.dataset.id}&name=PartInvoice&prefix=${e.currentTarget.dataset.code}&title=${encodeURI('备件箱单发票')}`);
    }

    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.brandName',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partInvoiceCode',
                defaultMessage: '发票号'
            }),
            sorter: true,
            dataIndex: 'partInvoiceCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.invoicedDate',
                defaultMessage: '发票日期'
            }),
            dataIndex: 'invoicedDate',
            sorter: true,
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.shipmentType',
                defaultMessage: '运输方式'
            }),
            dataIndex: 'shipmentType',
            render: text => conventEnumValueToString(transportType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.paymentType',
                defaultMessage: '付款方式'
            }),
            dataIndex: 'paymentType',
            render: text => conventEnumValueToString(paymentType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.priceTerms',
                defaultMessage: '价格条款'
            }),
            dataIndex: 'priceTerms',
            render: text => conventEnumValueToString(partOrderPriceTerms, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalAmount',
                defaultMessage: '备件总金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.invoiceAmount',
                defaultMessage: '发票金额'
            }),
            dataIndex: 'invoiceAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '发票状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(partContractInvoiceStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partShipmentCode',
                defaultMessage: '发运单号'
            }),
            dataIndex: 'partShipmentCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.listExcel,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="listExcel"
                                placement="topLeft"
                                onConfirm={this.listExcelConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.listExcel',
                                    defaultMessage: '是否导出预箱单？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.listExcel',
                                    defaultMessage: '预箱单导出'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.listExcel) && hasPermissions(r.options, PERMISSION.listExcel))
                    },
                    {
                        id: PERMISSION.invoiceExcel,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="invoiceExcel"
                                placement="topLeft"
                                onConfirm={this.invoiceExcelConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.invoiceExcel',
                                    defaultMessage: '是否导出预发票？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.invoiceExcel',
                                    defaultMessage: '预发票导出'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.invoiceExcel) && hasPermissions(r.options, PERMISSION.invoiceExcel))
                    },
                    {
                        id: PERMISSION.noticeExcel,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="noticeExcel"
                                placement="topLeft"
                                onConfirm={this.noticeExcelConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.noticeExcel',
                                    defaultMessage: '是否导出出运通知书？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.noticeExcel',
                                    defaultMessage: '出运通知书导出'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.noticeExcel) && hasPermissions(r.options, PERMISSION.noticeExcel))
                    },
                    {
                        id: PERMISSION.orderExcel,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="orderExcel"
                                placement="topLeft"
                                onConfirm={this.orderExcelConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.orderExcel',
                                    defaultMessage: '是否导出货运委托书？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.orderExcel',
                                    defaultMessage: '货运委托书导出'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.orderExcel) && hasPermissions(r.options, PERMISSION.orderExcel))
                    },
                    {
                        id: PERMISSION.confirmExcel,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="confirmExcel"
                                placement="topLeft"
                                onConfirm={this.confirmExcelConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.confirmExcel',
                                    defaultMessage: '是否导出出运确认书？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.confirmExcel',
                                    defaultMessage: '出运确认书导出'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.confirmExcel) && hasPermissions(r.options, PERMISSION.confirmExcel))
                    },
                    {
                        id: PERMISSION.packingExcel,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="packingExcel"
                                placement="topLeft"
                                onConfirm={this.packingExcelConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.packingExcel',
                                    defaultMessage: '是否导出箱单发票？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.packingExcel',
                                    defaultMessage: '箱单发票导出Excel'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.packingExcel) && hasPermissions(r.options, PERMISSION.packingExcel))
                    },
                    {
                        id: PERMISSION.packingPdf,
                        children: (
                            <a key="packingPdf" data-id={r.id} data-code={r.partInvoiceCode} onClick={this.onPrintPdf}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.packingPdf',
                                    defaultMessage: '箱单发票导出PDF'
                                })}
                            </a>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.packingPdf) && hasPermissions(r.options, PERMISSION.packingPdf))
                    },
                ];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


